package org.cresource.org.service.impl;

import org.cresource.basic.exception.BusinessException;
import org.cresource.basic.service.impl.BaseServiceImpl;
import org.cresource.basic.util.MD5Utils;
import org.cresource.basic.util.StrUtils;
import org.cresource.org.domain.Department;
import org.cresource.org.domain.Employee;
import org.cresource.org.domain.Shop;
import org.cresource.org.mapper.EmployeeMapper;
import org.cresource.org.mapper.ShopMapper;
import org.cresource.org.service.IEmployeeService;
import org.cresource.org.service.IShopService;
import org.cresource.user.domain.LoginInfo;
import org.cresource.user.domain.User;
import org.cresource.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    ShopMapper shopMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    LoginInfoMapper loginInfoMapper;

    @Override
    public void settlement(Shop shop) {
        //对用户进行校验
        // 1 判断是否存在，提示“已经入驻，请直接登陆！如果忘记了请找回密码！”
        Employee admin = shop.getAdmin();
        Employee employee = employeeMapper.loadByUser(admin);
        if (employee!=null)
            //不仅要错误，还要提示信息
            throw new BusinessException("已经入驻，请直接登陆！如果忘记了请找回密码！");
        // 2 如果不存在，走入驻流程
        // 2.1 保存管理员信息并放回自增id
        employeeMapper.save(admin);
        // 2.2 给shop添加admin.id，再保存Shop----名称可以重复但是店铺地址在方圆几公里不能重复入驻，由审核人员把控。
        shopMapper.save(shop);  //上一步保存完毕shop.admin里面就有id


        //让管理员关联店铺id
        admin.setShop(shop);
        employeeMapper.update(admin);
        LoginInfo loginInfo=employee2LoginInfo(admin);
        loginInfoMapper.save(loginInfo);

    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo logininfo = new LoginInfo();
       logininfo.setUsername(employee.getUsername());
       logininfo.setPhone(employee.getPhone());
       logininfo.setEmail(employee.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String password = employee.getPassword();
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        logininfo.setSalt(salt);
        logininfo.setPassword(md5Pwd);
        logininfo.setType(1);
        return logininfo;
    }









    @Override
    public void add(Shop shop) {
         Long admin_id= employeeMapper.loadIdByName(shop.getAdmin().getUsername());
        shop.setAdmin_id(admin_id);
         shopMapper.save(shop);
    }
}
